package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Sound;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SoundApiImpl implements SoundApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;


    //发送声音
    @Override
    public String saveSound(Sound sound) {
        //如果sound对象的id为空,则返回null
        if (sound.getUserId() == null) {
            return null;
        }
        sound.setId(ObjectId.get());
        sound.setCreated(System.currentTimeMillis());

        //自增长id
        sound.setSid(this.idWorker.getNextId("sound"));
        this.mongoTemplate.save(sound);
        return sound.getId().toString();
    }

    //接收声音
    @Override
    public List<Sound> receiveSound(Long userId) {
        //将自己排除掉
        Query query = Query.query(Criteria.where("userId").ne(userId));
        return this.mongoTemplate.find(query, Sound.class);
    }

}
